using B.S.RbacData.ErrorCode;
using ContentmanagementBase.Domain.Enums;
using ContentmanagementBaseRead.API.Applications.Commands.Hospitals;
using ContentmanagementBaseRead.API.Dtos;
using MediatR;
using System.ComponentModel;
using System.Reflection;

namespace ContentmanagementBaseRead.API.Applications.Commandhandlters.Hospitals
{
    /// <summary>
    /// 获取医院类型信息命令处理
    /// </summary>
    public class GetHospitalTypesCommandHandler : IRequestHandler<GetHospitalTypesCommand, ApiResult<List<HospitalTypeDto>>>
    {
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<GetHospitalTypesCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志记录器</param>
        public GetHospitalTypesCommandHandler(ILogger<GetHospitalTypesCommandHandler> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 处理获取医院类型信息命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public async Task<ApiResult<List<HospitalTypeDto>>> Handle(GetHospitalTypesCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取医院类型信息");

                var hospitalTypes = new List<HospitalTypeDto>();

                // 获取所有医院类型枚举值
                var enumValues = Enum.GetValues(typeof(HospitalTypeEnum)).Cast<HospitalTypeEnum>();

                foreach (var enumValue in enumValues)
                {
                    var fieldInfo = typeof(HospitalTypeEnum).GetField(enumValue.ToString());
                    var descriptionAttribute = fieldInfo?.GetCustomAttribute<DescriptionAttribute>();

                    hospitalTypes.Add(new HospitalTypeDto
                    {
                        Value = enumValue,
                        Name = enumValue.ToString(),
                        Description = descriptionAttribute?.Description ?? enumValue.ToString()
                    });
                }

                _logger.LogInformation("医院类型信息获取成功，共获取到 {Count} 个类型", hospitalTypes.Count);

                return new ApiResult<List<HospitalTypeDto>>
                {
                    code = ResultEnumCode.Ok,
                    message = "医院类型信息获取成功",
                    data = hospitalTypes
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取医院类型信息过程中发生异常");
                return new ApiResult<List<HospitalTypeDto>>
                {
                    code = ResultEnumCode.fails,
                    message = $"获取医院类型信息失败：{ex.Message}",
                    data = new List<HospitalTypeDto>()
                };
            }
        }
    }
} 